package com.bainuo.doctor.common.image_support.filedownload;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.bainuo.doctor.common.model.FileDownLoadTask;
import com.blankj.utilcode.utils.LogUtils;
import com.global.Global;
import com.orhanobut.hawk.Hawk;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class FileDownLoadManager extends FileDownloader implements FileDownloadListener{

//	private static FileDownLoadManager instance;
	private static Map<String,FileDownLoadManager> instanceMap = new HashMap<>();

	private FileDownloadMangerListener _managerListener;
	private String rootDir;


	private Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);


			if (msg.what == 0){
				if (_managerListener != null) {
					_managerListener.onTaskStatusChange((FileDownLoadTask) msg.obj);
				}
			}else{
				handler.removeMessages(msg.what);
				if (_managerListener != null) {
					_managerListener.onTaskProgressChange((FileDownLoadTask) msg.obj);
				}
			}
		}
	};

	protected FileDownLoadManager(String path){
		rootDir = path;
		setDownloadListener(this);
		initTask();
	};

	public static FileDownLoadManager getInstance() {
		return getInstance(null);
	}

	public static FileDownLoadManager getInstance(String direct) {
		if(TextUtils.isEmpty(direct)){
			direct = "default";
		}
		FileDownLoadManager instance = instanceMap.get(direct);
		if (instance == null) {
			instance = new FileDownLoadManager(direct);
			instanceMap.put(direct,instance);
		}
		return instance;
	}


	public void initTask() {

		String root = userRootPath();
		File rootFile = new File(root);
		String[] subLists = rootFile.list();
		if(subLists == null) return;
		//遍历子目录
		for (String subTmp : subLists) {

			String tid = subTmp;
			//判断是否是tmp临时文件
			if(subTmp.endsWith(FileDownLoadTask.EXT_TMP)){
				tid = subTmp.substring(0,subTmp.length()-FileDownLoadTask.EXT_TMP.length());
			}

			int fileSize = Hawk.get(tid,0);
			//LogUtils.e("initTask file--->"+tid+" size "+fileSize);

			if(fileSize != 0){


				FileDownLoadTask task = new FileDownLoadTask();

				task.setTid(tid);
				task.setSavePath(getPath(task.getTid()));

				if(Hawk.get(tid+FileDownLoadTask.EXT_JSON) != null){
					task.setJsonComplete(true);
				}

				//如果名字已更变 则已下载完成
				if (tid  == subTmp) {
					task.setStatus(FileDownLoadTask.TASK_STATUS.STATUS_DOWNLOAD_FINISH);
					task.setProgress(1);
					task.setUpdateTime((String) Hawk.get(FileDownLoadTask.getUpdateTimeKey(tid)));

				}else{

					File subFile = new File(getPath(subTmp));
					int cfs = (int)subFile.length();
					if (cfs == fileSize){
						subFile.renameTo(new File(task.getSavePath()));
						task.setStatus(FileDownLoadTask.TASK_STATUS.STATUS_DOWNLOAD_FINISH);
						task.setUpdateTime((String) Hawk.get(FileDownLoadTask.getUpdateTimeKey(tid)));
						task.setProgress(1);
					}else if (cfs < fileSize){
						task.setDownloadedLength(cfs);
						task.setProgress(cfs*1.0f/fileSize);
						task.setStatus(FileDownLoadTask.TASK_STATUS.STATUS_DOWNLOAD_PAUSE);
					}else{
						//文件大于长度 则删除
						subFile.delete();
						task = null;
					}
				}

				if (task != null) {
					task.setFileSize(fileSize);
					_taskMap.put(tid, task);
					//LogUtils.e("", "init task name ->" + tid + " fs " + fileSize + " pro" + task.getProgress());
				}

			}
		}
	}

	public void retryAllTask(){

        for (FileDownLoadTask task : _taskMap.values()){
			if (task.getStatus() == FileDownLoadTask.TASK_STATUS.STATUS_DOWNLOAD_FINISH
					&& !new File(task.getSavePath()).exists()){
				clearTask(task.getTid());
			}
            download(task.getUrl(),task.getTid(),false,"0");
        }
    }

	public String addDownloadFile(String id,String path){

		if (path == null && id == null ) return null;

		File file = new File(path);
		Hawk.put(id,(int)file.length());
		String dst = getPath(id);
		file.renameTo(new File(dst));


		FileDownLoadTask task = new FileDownLoadTask();
		task.setTid(id);
		task.setSavePath(getPath(task.getTid()));
		task.setStatus(FileDownLoadTask.TASK_STATUS.STATUS_DOWNLOAD_FINISH);
		_taskMap.put(id,task);

		return dst;
    }


	//重新下载文件
//	public void reDownload(String url ,String tid,boolean catalog){
//		clearTask(tid);
//		download(url,tid,catalog);
//	}


//	public void downloadWithCatalog(String url ,String tid){
//		download(url,tid,true);
//	}
//
//	public void download(String url ,String tid) {
//		download(url,tid,false);
//	}

	public void download(String url ,String tid ,boolean catalog,String updateTime){

		if (TextUtils.isEmpty(url) || TextUtils.isEmpty(tid)) {
			return;
		}

		FileDownLoadTask task = _taskMap.get(tid);
		if(task == null){
			task = new FileDownLoadTask();

			task.setStatus(FileDownLoadTask.TASK_STATUS.STATUS_DOWNLOAD_PRE);
			taskStatusChange(task);

		}else{

			if (task.getStatus() == FileDownLoadTask.TASK_STATUS.STATUS_DOWNLOADING
					|| task.getStatus() == FileDownLoadTask.TASK_STATUS.STATUS_DOWNLOAD_FINISH)
			return;

		}

		task.setTid(tid);
		task.setUrl(url);
		task.setUpdateTime(updateTime);

		if (task.getSavePath() == null) {
			task.setSavePath(getPath(task.getTid()));
		}


		task.setStatus(FileDownLoadTask.TASK_STATUS.STATUS_DOWNLOAD_PRE);
		taskStatusChange(task);
		_taskMap.put(task.getTid(),task);

		//task.setUrl("http://down.tech.sina.com.cn/download/d_load.php?d_id=40975&down_id=5&ip=58.250.243.24");

		if (!catalog) {
			task.setJsonComplete(true);
		}

		startDownload(task);


	}

	public void clearTask(String tid){

		if (!TextUtils.isEmpty(tid)){
			_taskMap.remove(tid);
			new File(getPath(tid)).delete();
			new File(getPath(tid+FileDownLoadTask.EXT_TMP)).delete();
			Hawk.delete(FileDownLoadTask.getJsonKey(tid));
			Hawk.delete(FileDownLoadTask.getUpdateTimeKey(tid));
			Hawk.delete(tid);
		}

	}


	private String userRootPath(){
		return Global.getPathWithRoot(rootDir);
	}
	private String getPath(String sub){
		String path = userRootPath();
		return path+ File.separator+sub;
	}


	/**
	 * 获取文件路径
	 * @param taskId
	 * @return
	 */
	public String getFilePath(String taskId){
		synchronized (this) {
			FileDownLoadTask task = _taskMap.get(taskId);
			return task==null?null:task.getSavePath();
		}
	}

	public String getFileUpdateTime(String taskId){
		synchronized (this) {
			FileDownLoadTask task = _taskMap.get(taskId);
			//如果没有下载完成 不返回

			return task==null?null:task.getUpdateTime();

		}
	}


	//开始下载
	public void onDownloadStart(FileDownLoadTask aTask){
		taskStatusChange(aTask);
	}

	@Override
	public void onDownloadPause(FileDownLoadTask aTask) {
		taskStatusChange(aTask);
	}

	@Override
	public void onDownloadCancel(FileDownLoadTask aTask) {
		taskStatusChange(aTask);
	}

	@Override
	public void onDownloadSuccess(FileDownLoadTask aTask) {
		if(aTask.getUpdateTime() != null){
			Hawk.put(FileDownLoadTask.getUpdateTimeKey(aTask.getTid()),aTask.getUpdateTime());
		}

		taskStatusChange(aTask);
	}

	@Override
	public void onDownloadFailed(FileDownLoadTask aTask) {
		taskStatusChange(aTask);
	}

//状态变化
	private void taskStatusChange(FileDownLoadTask aTask){

		Message msg = Message.obtain(handler,0,aTask);
		handler.sendMessage(msg);
	}

	@Override
	public void onDownloadProgress(FileDownLoadTask aTask) {
		Message msg = Message.obtain(handler,1,aTask);
		handler.sendMessage(msg);
	}



	public FileDownloadMangerListener getListener() {
		return this._managerListener;
	}

	public void setListener(FileDownloadMangerListener aListener) {
		this._managerListener = aListener;
	}


	public void addListener(FileDownloadMangerListener aListener) {
		this._managerListener = aListener;
	}

//	public static String getCatalogKey(String id){
//		return FileDownLoadTask.getJsonKey(id);
//	}


}
